/*
 * Copyright (c) 2018-2999 湖南洛云网络科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.platform.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.model.Category;
import com.yami.shop.bean.model.Product;
import com.yami.shop.common.annotation.SysLog;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.i18n.LanguageEnum;
import com.yami.shop.platform.config.PlatformConstant;
import com.yami.shop.security.platform.util.SecurityUtils;
import com.yami.shop.service.CategoryService;
import com.yami.shop.common.config.Constant;
import com.yami.shop.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 分类管理
 * @author lgh
 *
 */
@RestController
@RequestMapping("/prod/category")
public class CategoryController {

	@Autowired
	private CategoryService categoryService;

	@Autowired
	private ProductService productService;


	/**
	 * 获取分类信息
	 */
	@GetMapping("/info/{categoryId}")
	public ResponseEntity<Category> info(@PathVariable("categoryId") Long categoryId){
		Category category = categoryService.getCategoryByCategoryId(categoryId);

		return ResponseEntity.ok(category);
	}

	/**
	 * 保存分类
	 */
	@SysLog("保存分类")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('prod:category:save')")
	public ResponseEntity<Void> save(@RequestBody Category category){
		category.setShopId(Constant.PLATFORM_SHOP_ID);
		category.setRecTime(new Date());
//		int count = categoryService.count(new LambdaQueryWrapper<Category>().eq(Category::getCategoryName, category.getCategoryName())
//				.eq(Category::getParentId, category.getParentId()).eq(Category::getShopId,Constant.PLATFORM_SHOP_ID))
		Integer count = categoryService.getCategoryName(category);
		if(count > 0){
			// 类目名称已存在
			throw new YamiShopBindException(I18nMessage.getMessage("yami.category.name.exist"));
		}
		category.setGrade(getGradeByParentId(category.getParentId()));
		category.setSuperiorId(-1L);
		// 获取上级的上级
		if(category.getGrade() == PlatformConstant.MAX_CATEGORY_GRADE) {
			Long superiorId = categoryService.getParentCategoryByParentId(category.getParentId());
			category.setSuperiorId(superiorId);
		}
		categoryService.saveCategroy(category);
		// 清除缓存
		removeCategoryCacheByParentId(category);
		return ResponseEntity.ok().build();
	}


	/**
	 * 更新分类
	 */
	@SysLog("更新分类")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('prod:category:update')")
	public ResponseEntity<String> update(@RequestBody Category category){
		category.setShopId(Constant.PLATFORM_SHOP_ID);
		Category categoryDb = categoryService.getById(category.getCategoryId());
		if (Objects.equals(categoryDb.getParentId(), Constant.CATEGORY_ID) && !Objects.equals(category.getParentId(), Constant.CATEGORY_ID)){
			// 一级分类不能改为二级分类
			return ResponseEntity.badRequest().body(I18nMessage.getMessage("yami.category.one.check"));
		}else if(Objects.equals(category.getParentId(), Constant.CATEGORY_ID) && !Objects.equals(categoryDb.getParentId(), Constant.CATEGORY_ID)){
			// 二级分类不能改为一级分类
			return ResponseEntity.badRequest().body(I18nMessage.getMessage("yami.category.two.check"));
		}
		if (Objects.equals(category.getParentId(),category.getCategoryId())) {
			// 分类的上级不能是自己本身
			return ResponseEntity.badRequest().body(I18nMessage.getMessage("yami.category.superior.check"));
		}

		Integer count = categoryService.getCategoryName(category);
		if(count > 0){
			// 类目名称已存在
			throw new YamiShopBindException(I18nMessage.getMessage("yami.category.name.exist"));
		}
        // 如果从下线改成正常，则需要判断上级的状态
        if (Objects.equals(categoryDb.getStatus(),0) && Objects.equals(category.getStatus(),1) && !Objects.equals(category.getParentId(),0L)){
            Category parentCategory = categoryService.getOne(new LambdaQueryWrapper<Category>().eq(Category::getCategoryId, category.getParentId()));
            if(Objects.isNull(parentCategory) || Objects.equals(parentCategory.getStatus(),0)){
                // 修改失败，上级分类不存在或者不为正常状态
                throw new YamiShopBindException("yami.category.status.check");
            }
        }
		category.setGrade(getGradeByParentId(category.getParentId()));
		category.setOldCategoryName(categoryDb.getCategoryName());
		category.setSuperiorId(-1L);
		// 获取上级的上级
		if(category.getGrade() == PlatformConstant.MAX_CATEGORY_GRADE) {
			Long superiorId = categoryService.getParentCategoryByParentId(category.getParentId());
			category.setSuperiorId(superiorId);
		}
		categoryService.updateCategroy(category);
		// 清除缓存
		removeCategoryCacheByParentId(category);
		return ResponseEntity.ok().build();
	}

	/**
	 * 删除分类
	 */
	@SysLog("删除分类")
	@DeleteMapping("/{categoryId}")
	@PreAuthorize("@pms.hasPermission('prod:category:delete')")
	public ResponseEntity<String> delete(@PathVariable("categoryId") Long categoryId){
		if (categoryService.count(new LambdaQueryWrapper<Category>().eq(Category::getParentId,categoryId)) >0) {
			// 请删除子分类，再删除该分类
			return ResponseEntity.badRequest().body(I18nMessage.getMessage("yami.category.delete.child"));
		}
		int categoryProdCount = productService.count(new LambdaQueryWrapper<Product>().eq(Product::getCategoryId, categoryId).ne(Product::getStatus, -1));
		if (categoryProdCount>0){
			// 该分类下还有商品，请先删除该分类下的商品
			return ResponseEntity.badRequest().body(I18nMessage.getMessage("yami.category.delete.check"));
		}
		Category category = categoryService.getById(categoryId);
		category.setSuperiorId(-1L);
		// 获取上级的上级
		if(category.getGrade() == PlatformConstant.MAX_CATEGORY_GRADE) {
			Long superiorId = categoryService.getParentCategoryByParentId(category.getParentId());
			category.setSuperiorId(superiorId);
		}
		categoryService.deleteCategroy(category);
		// 清除缓存
		removeCategoryCacheByParentId(category);
		return ResponseEntity.ok().build();
	}

	/**
	 * 所有的
	 */
	@GetMapping("/listCategory")
	public ResponseEntity<List<Category>> listCategory(@RequestParam(value = "maxGrade", required = false, defaultValue = "2") Integer maxGrade,
                                                       @RequestParam(value = "status", required = false) Integer status) {

		List<Category> categories =  categoryService.listByLang(I18nMessage.getLang(),maxGrade,null,status,Constant.PLATFORM_SHOP_ID);
		return ResponseEntity.ok(categories);
	}

	/**
	 * 根据等级与状态获取平台分类列表
	 * @param grade
	 * @param status
	 * @return
	 */
	@GetMapping("/listCategoryByGrade")
	public ResponseEntity<List<Category>> listCategoryByGrade(@RequestParam(value = "grade", defaultValue = "2") Integer grade, @RequestParam(value = "status", required = false) Integer status) {
		List<Category> categories = categoryService.listByGrade(I18nMessage.getLang(), grade, status, Constant.PLATFORM_SHOP_ID);
		return ResponseEntity.ok(categories);
	}

    /**
     * 获取上架分类和当前选中分类的父类
     */
    @GetMapping("/upAndCurrCategoryList/{categoryId}")
    public ResponseEntity<List<Category>> upAndCurrCategoryList(
            @RequestParam(value = "maxGrade", required = false, defaultValue = "2") Integer maxGrade,
            @PathVariable("categoryId") Long categoryId){
		Category category = new Category();
		category.setLang(I18nMessage.getDbLang());
		category.setStatus(1);
		category.setShopId(Constant.PLATFORM_SHOP_ID);
		category.setGrade(maxGrade);
		//获取上架的分类
        List<Category> upList = categoryService.categoryList(category);

        //如果是新增的，直接返回上架的分类即可
        if (categoryId==0){
            return ResponseEntity.ok(upList);
        }
		Category currCategory = categoryService.getCategoryByCategoryId(categoryId);
		if (currCategory == null) {
			return ResponseEntity.ok(upList);
		}
		while (currCategory.getParentId() != 0) {
			currCategory=categoryService.getCategoryByCategoryId(currCategory.getParentId());
			if (!Objects.equals(currCategory.getStatus(), 1)) {
				upList.add(currCategory);
			}
        }
        return ResponseEntity.ok(upList);
    }

//	/**
//	 * 所有的
//	 */
//	@GetMapping("/listCategory")
//	public ResponseEntity<List<Category>> listCategory(Long shopId){
//		shopId = shopId == null ? SecurityUtils.getSysUser().getShopId():shopId;
//		return ResponseEntity.ok(categoryService.list(new LambdaQueryWrapper<Category>()
//				.le(Category::getGrade, 2)
//				.eq(Category::getShopId, shopId)
//				.orderByAsc(Category::getSeq)));
//	}


	private int getGradeByParentId(Long parentId) {
		// 如果上级为id为0，则设置分类等级为0
		if (Objects.equals(parentId,0L)) {
			return 0;
		}
		Category parentCategory = categoryService.getById(parentId);
		return parentCategory.getGrade() + 1;
	}

	/**
	 * 平台的分类
	 */
	@GetMapping("/platformCategory")
	public ResponseEntity<List<Category>> platformCategory(@RequestParam(value = "maxGrade",required = false) Integer maxGrade,
														   @RequestParam(value = "status",required = false) Integer status){

		List<Category> list =  categoryService.listByLang(I18nMessage.getLang(),maxGrade,null, status, Constant.PLATFORM_SHOP_ID);
		return ResponseEntity.ok(list);
	}

	private void removeCategoryCacheByParentId(Category category) {
		categoryService.removeCacheByParentIdAndLang(category.getParentId(), category.getShopId(), LanguageEnum.LANGUAGE_ZH_CN.getLang());
		categoryService.removeCacheByParentIdAndLang(category.getParentId(), category.getShopId(), LanguageEnum.LANGUAGE_EN.getLang());
		categoryService.removeCacheByParentIdAndLang(category.getSuperiorId(), category.getShopId(), LanguageEnum.LANGUAGE_ZH_CN.getLang());
		categoryService.removeCacheByParentIdAndLang(category.getSuperiorId(), category.getShopId(), LanguageEnum.LANGUAGE_EN.getLang());
	}
}
